package com.onairm.baselibrary.update;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.onairm.baselibrary.R;
import com.onairm.baselibrary.utils.TipToast;
import com.onairm.baselibrary.utils.Utils;


import org.apache.http.conn.ConnectTimeoutException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;

public class UpdateManager implements View.OnClickListener {
    /*下载中*/
    private static final int DOWNLOAD = 1;
    /*下载完成*/
    private static final int DOWNLOAD_FINISH = 2;
    private String mSavePath; //下载保存路径
    private int progress;//记录进度条数
    private boolean cancelUpdate = false;//是否取消更新
    private Context mContext;
    private TextView updata_version_sure;
    private TextView updata_version_cancle;
    private TextView update_message;
    private Dialog builder;
    /*更新进度条*/
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;
    private VersionInfo chickUpEntity;
    private String ipan;
    private TextView updata_down_cancle;
    private String apkName = "update.apk";

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    update_length.setText("已下载" + progress + "%");
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();
                    break;
                case 3:
                    // 显示提示对话框
                    if(null != sureListener){
                        if(sureListener.clickSure()){
                            showNoticeDialog();
                        }
                    }
                    break;
                case 4:
                    if (ipan.equals("2")) {
                        TipToast.longTip("当前已是最新版本");
                    } else {

                    }
                    break;
                default:
                    break;
            }
        }
    };
    private TextView update_length;

    public UpdateManager(Context context, String ipan) {
        this.mContext = context;
        this.ipan = ipan;
    }

    /**
     * 检查软件更新
     */
    public void checkUpdate(VersionInfo versionInfo) {
        isUpdate(versionInfo);
    }

    private void showNoticeDialog() {
        // TODO Auto-generated method stub
        // 构造对话框
        builder = new Dialog(mContext, R.style.UpdateDialogStyle);
        Window window = builder.getWindow();
        window.setContentView(R.layout.update_dialog);
        initDialog(window);
        builder.setCanceledOnTouchOutside(true);//设置点击Dialog
        builder.setCanceledOnTouchOutside(false);
        builder.show();
    }


    private void initDialog(Window window) {
        // TODO Auto-generated method stub
        update_message = (TextView) window.findViewById(R.id.update_message);
        if (chickUpEntity != null)
            update_message.setText(chickUpEntity.getDescription());

        updata_version_sure = (TextView) window.findViewById(R.id.updata_version_sure);
        updata_version_sure.setOnClickListener(this);

        updata_version_cancle = (TextView) window.findViewById(R.id.updata_version_cancle);
        updata_version_cancle.setOnClickListener(this);
    }

    /**
     * 检查软件是否有更新
     */
    private void isUpdate(VersionInfo versionInfo) {
        chickUpEntity = versionInfo;
        if (compareVersionUpdate(chickUpEntity)) {
            mHandler.sendEmptyMessage(3);
        } else {
            mHandler.sendEmptyMessage(4);
        }
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        mDownloadDialog = new Dialog(mContext, R.style.UpdateDialogStyle);
        Window window = mDownloadDialog.getWindow();
        window.setContentView(R.layout.update_down_dialog);
        initDownDialog(window);
        mDownloadDialog.setCanceledOnTouchOutside(false);//设置点击Dialog
        mDownloadDialog.show();
        downloadApk();
    }

    private void initDownDialog(Window window) {
        mProgress = (ProgressBar) window.findViewById(R.id.update_down_progress);
        update_length = (TextView) window.findViewById(R.id.update_length);
        updata_down_cancle = (TextView) window.findViewById(R.id.updata_down_cancle);
        updata_down_cancle.setOnClickListener(this);
    }

    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    Log.e("Updatem", chickUpEntity.getUrl());
                    URL url = new URL(chickUpEntity.getUrl());
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();
                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, apkName);
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            mDownloadDialog.dismiss();
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
                TipToast.shortTip("MalformedURLException");
            } catch (UnknownHostException e) {
                TipToast.shortTip("网络连接失败，请稍后重试");
                mDownloadDialog.dismiss();
            } catch (ConnectTimeoutException e) {
                e.printStackTrace();
                TipToast.shortTip("网络连接失败，请稍后重试");
                mDownloadDialog.dismiss();
            } catch (SocketException e) {
                TipToast.shortTip("网络连接失败，请稍后重试");
                mDownloadDialog.dismiss();
            } catch (SocketTimeoutException e) {
                e.printStackTrace();
                TipToast.shortTip("SocketTimeoutException");
                TipToast.shortTip("网络连接失败，请稍后重试");
                mDownloadDialog.dismiss();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mDownloadDialog.dismiss();
        }
    }

    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkfile = new File(mSavePath, apkName);
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        // 判断版本大于等于7.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            data = FileProvider.getUriForFile(mContext, "com.onairm.videomessage4android.fileProvider", apkfile);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            data = Uri.fromFile(apkfile);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.updata_version_sure) {
            builder.dismiss();
            showDownloadDialog();

        } else if (i == R.id.updata_version_cancle) {
            builder.dismiss();
            if (chickUpEntity.getMustUpdate() == 1) {
                if (forceQuitLister != null)
                    forceQuitLister.todoForce();
            }
        } else if (i == R.id.updata_down_cancle) {
            mDownloadDialog.dismiss();
            // 设置取消状态
            cancelUpdate = true;
            if (chickUpEntity.getMustUpdate() == 1) {
                if (forceQuitLister != null) {
                    forceQuitLister.todoForce();
                }
            }
        }
    }


    private boolean compareVersionUpdate(VersionInfo versionInfo) {
        if (versionInfo != null) {
            String netVersion = versionInfo.getVersion();
            String version = Utils.getVersion();
            if (compareVersion(netVersion, version)) {
                return true;
            }
        }
        return false;
    }

    private boolean compareVersion(String netVersion, String localVersion) {
        String[] arr1 = netVersion.split("\\.");
        String[] arr2 = localVersion.split("\\.");
        for (int i = 0; i < arr1.length; i++) {
            if (i >= arr2.length) {
                return false;
            }
            if (Integer.parseInt(arr1[i]) > Integer.parseInt(arr2[i])) {
                return true;
            }
            if (Integer.parseInt(arr1[i]) < Integer.parseInt(arr2[i])) {
                return false;
            }
        }
        return false;
    }


    public interface ForceQuitLister {
        void todoForce();
    }

    public interface SureListener{
        boolean clickSure();
    }
    private ForceQuitLister forceQuitLister;
    private SureListener sureListener;

    public void setForceQuitLister(ForceQuitLister forceQuitLister) {
        this.forceQuitLister = forceQuitLister;
    }
    public void setSureListener(SureListener sureListener){
        this.sureListener=sureListener;
    }

    public  boolean isShowTipDialog(){
        boolean result=false;
        if(null != builder){
            result=builder.isShowing();
        }
        return result;
    }

}
